<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
// import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { busAdd, busInfoByGroupId, busUpdate } from '#/api/register/bus/group';
import { taskList } from '#/api/register/bus/task';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '修改巴士任务' : '加入巴士任务';
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 110,
  },
  schema: [
    {
      label: '巴士ID',
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
    },
    {
      label: '参观团ID',
      fieldName: 'groupId',
      component: 'Input',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
    },
    {
      label: '巴士任务',
      fieldName: 'taskId',
      component: 'Select',
      componentProps: {
        options: [],
        showSearch: true,
      },
      rules: 'selectRequired',
    },
    {
      label: '团体横幅',
      component: 'RadioGroup',
      fieldName: 'bannerType',
      componentProps: {
        buttonStyle: 'solid',
        options: getDictOptions(DictEnum.BUS_BANNER_TYPE, true),
        optionType: 'button',
      },
      defaultValue: 1,
      rules: 'selectRequired',
    },
    {
      label: '备注',
      fieldName: 'remark',
      component: 'Textarea',
      componentProps: {
        autoSize: { minRows: 3 },
      },
    },
  ],
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { groupId, update } = modalApi.getData() as {
      groupId: number | string;
      update?: boolean;
    };
    isUpdate.value = !!update;
    await formApi.setValues({ groupId });

    if (isUpdate.value) {
      const record = await busInfoByGroupId(groupId);
      await formApi.setValues(record);
    }

    // 查询巴士任务集合
    const list = (await taskList()) ?? [];
    formApi.updateSchema([
      {
        fieldName: 'taskId',
        componentProps: {
          optionFilterProp: 'label',
          options: list.map((item) => {
            return { label: item.name, value: item.id };
          }),
        },
      },
    ]);

    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? busUpdate(data) : busAdd(data));
    // console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[650px]">
    <BasicForm />
  </BasicModal>
</template>
